﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Xml;
using Warensoft.Unity.Communication.Client.Contracts;
using Warensoft.Unity.Communication.Client.Models;
using Warensoft.Unity.Communication.DbClient;

namespace Warensoft.Unity.Communication.Client.DbClient
{
    public class DbHelper
    {

        private HttpClient httpClient = null;
        public string ConnectionUrl { get; set; }

        /// <summary>
        /// DbHelper构造函数
        /// </summary>
        /// <param name="connectionUrl">数据库服务地址</param>
        public DbHelper(string connectionUrl)
        {
            this.httpClient = UnityCommunicationManager.CreateInstance().GetHttpClient();
            this.ConnectionUrl = connectionUrl;
        }
        private void CreateDBOperation(string command,Query query, Action<ResultInfo> callback)
        {
            this.httpClient.BeginPostHttpContent(this.ConnectionUrl + "?Command="+command, query.ToArray(), new Action<byte[]>(buffer =>
            {
                ResultInfo result = ResultInfo.Create(buffer);
                callback(result);

            }));
        }
        /// <summary>
        /// 返回一个数据集
        /// </summary>
        public void CreateDataSet(Query query, Action<ResultInfo> callback)
        {

            this.CreateDBOperation("CreateDataSet",query,callback);
        }


        /// <summary>
        /// 执行只返回一个值的SQL语句
        /// </summary>
        public void ExecuteScalar(Query query, Action<ResultInfo> callback)
        {
            this.CreateDBOperation("ExecuteScalar", query, callback);
        }

      
        
        /// <summary>
        /// 执行非选择性操作
        /// </summary>
        public void ExecuteNonQuery(Query query, Action<ResultInfo> callback)
        {
            this.CreateDBOperation("ExecuteNonQuery", query, callback);
        }


        /// <summary>
        /// 返回一个具备数据表结构的空数据集
        /// </summary>
        public void CreateDataSetSchema(string tableName, Action<ResultInfo> callback)
        {
            Query query = new Query();
            query.CommandText = tableName;
            this.CreateDBOperation("CreateDataSetSchema", query, callback);
        }
        /// <summary>
        /// 更新数据集，包括添加、修改、删除
        /// </summary>
        /// <param name="ds">数据集</param>
        /// <param name="tableName">对应的表名</param>
        /// <returns></returns>
        public void UpdateDataSet(DataSet ds, string tableName, Action<ResultInfo> callback)
        {
            Query query = new Query();
            query.CommandText = tableName;
            query.DataSet = ds;
            this.CreateDBOperation("UpdateDataSet", query, callback);
        }
    }
}
